<!--这是患者管理页面-->
<template>
  <div class="common-layout">
    <el-container>
      <!--展示患者基本信息和操作-->
      <el-header style="padding: 0; height: 20vh;" >
        <el-card shadow="never" style="background-color: #E0F7FA" >
          <el-row :gutter="20">
            <!--选择患者的下拉选框，用于返回患者id-->
            <el-col :span="3" style="border: #3b82f6 solid 2px;padding-bottom: 10px;">
              <div style="font-size: 14px;font-weight: bold;display: flex;align-items: center;margin: 10px 0 10px 10px;">
                <el-icon><Avatar /></el-icon>
                <span>当前就诊患者：</span>
              </div>
              <el-select placeholder="请选择患者" v-model="selectedId" @change="selectPatient" style="width: 100%;">
                <el-option v-for="item in patientArr" :label="item.name" :value="item.patientId"></el-option>
              </el-select>
            </el-col>
            <!--根据患者的id，展示患者的具体信息-->
            <el-col :span="11" style="margin: auto 0">
              <el-table :data="patientById" style="width: 100%;">
                <el-table-column prop="name" label="患者姓名" width="100" align="center" />
                <el-table-column prop="gender" label="性别" width="75" align="center" />
                <el-table-column prop="age" label="年龄" width="75" align="center" />
                <el-table-column prop="phoneNum" label="手机号" width="125" align="center" />
                <el-table-column prop="personId" label="身份证号" width="175" align="center"/>
              </el-table>
            </el-col>
            <!--用于输入患者的主诉-->
            <el-col :span="4">
              <span style="font-size: 14px;font-weight: bold">患者主诉：</span>
              <el-input
                  v-model="chiefComplaint"
                  maxlength="50"
                  style="width: 100%;margin-top: 5px"
                  placeholder="请输入患者主诉："
                  show-word-limit
                  type="textarea"
                  :autosize="{minRows: 3,maxRows: 3}"
                  resize="none"
              />
            </el-col>
            <!--用于输入患者的既往病史-->
            <el-col :span="4">
              <span style="font-size: 14px;font-weight: bold">既往病史：</span>
              <el-input
                  v-model="pastMedicalHistory"
                  maxlength="50"
                  style="width: 100%;margin-top: 5px"
                  placeholder="请输入既往病史："
                  show-word-limit
                  type="textarea"
                  :autosize="{minRows: 3,maxRows: 3}"
                  resize="none"
              />
            </el-col>
            <!--完成接诊和退号按钮-->
            <el-col :span="2">
              <el-button type="success" style="width: 100%;margin: 15px auto;" :disabled="canNotFinish()"
                         @click="changeAttendanceRecordStatus('30')">完成接诊</el-button>
              <el-button type="danger" style="width: 100%;margin: 0 auto;" :disabled="canNotRefuse()"
                         @click="changeAttendanceRecordStatus('40')">退号</el-button>
            </el-col>
          </el-row>
        </el-card>
      </el-header>
      <!--展示患者检查单信息和处方单信息以及对应的操作-->
      <el-main style="padding: 0">
        <!--展示患者检查单-->
        <el-card shadow="never" style="height: 35vh;background-color:#FFFFF0;margin-bottom: 5px;">
          <el-row :gutter="20">
            <!--展示检查单信息(价格、医保价格)和基本操作-->
            <el-col :span="4" style="border: #3b82f6 solid 2px; margin: auto 0">
              <div style="font-size: 14px;font-weight: bold;text-align: center;">当前就诊患者的检查单信息：</div>
              <el-button type="primary" style="width: 100%;margin: 5px auto;" @click="showAddInspectionSub"
                         :disabled="canNotAddInspectionItem()">新增检查项</el-button>
              <div style="text-align: center;margin-bottom: 5px;">检查单原始金额：￥{{totalInspectionPrice}}</div>
              <div style="text-align: center;margin-bottom: 5px;">检查单医保金额：￥{{totalInsuranceInspectionPrice}}</div>
              <el-button v-if="inspectionStatus==='05'" type="primary" style="width: 100%;margin: 0 auto;"
                         :disabled="inspectionSubArrIsEmpty()" @click="commitInspection">提交检查单</el-button>
              <div v-else style="font-size: 14px;font-weight: bold;text-align: center;">检查单已提交，备注如下：</div>
              <el-input
                  :disabled="inspectionStatus!=='05'"
                  v-model="inspectionRemark"
                  maxlength="50"
                  style="width: 100%;margin: 5px auto;"
                  placeholder="请输入检查单备注："
                  show-word-limit
                  type="textarea"
                  :autosize="{minRows: 3,maxRows: 3}"
                  resize="none"
              />
            </el-col>
            <!--展示检查单子项信息和基本操作-->
            <el-col :span="20" style="margin: auto 0">
              <div style="text-align: center;margin-bottom: 2px;">当前就诊患者的检查项目明细</div>
              <el-table :data="inspectionSubArr" style="width: 100%;height: 28vh;">
                <el-table-column prop="name" label="检查项目" align="center" />
                <el-table-column prop="reason" label="检查原因" align="center" />
                <el-table-column prop="standard" label="检查标准" align="center" />
                <el-table-column prop="status" label="状态" align="center"
                                 :formatter="inspectionSubItemStatusFormatter"/>
                <el-table-column prop="updateTime" label="更新时间" align="center"
                                 :formatter="inspectionSubItemUpdateTimeFormatter"/>
                <!--每行都有“查看结果”的按钮，result是静态资源的url，可以直接查看，如果!Scope.row.result，则禁用按钮-->
                <el-table-column label="检查结果" align="center">
                  <template #default="scope">
                    <el-button link type="primary" @click="showResult(scope.row.result)"
                               :disabled="!scope.row.result">查看结果</el-button>
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="价格" align="center"/>
                <el-table-column prop="insurancePrice" label="医保价格" align="center"/>
                <el-table-column label="操作" align="center">
                  <template #default="scope">
                    <el-button link type="primary" @click="editInspectionSub(scope.row.inspectionItemId,scope.row.name)"
                               :disabled="inspectionStatus!=='05'">编辑</el-button>
                    <el-button link type="primary" @click="deleteInspectionSub(scope.row.inspectionItemId,scope.row.price,
                               scope.row.insurancePrice)" :disabled="inspectionStatus!=='05'">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-card>
        <!--展示患者处方单-->
        <el-card shadow="never" style="height: 35vh;background-color:#FFF8DC;">
          <el-row :gutter="20">
            <!--展示处方单信息(价格、医保价格)和基本操作-->
            <el-col :span="4" style="border: #3b82f6 solid 2px; margin: auto 0">
              <div style="font-size: 14px;font-weight: bold;text-align: center;">当前就诊患者的处方单信息：</div>
              <el-button type="primary" style="width: 100%;margin: 5px auto;" @click="showAddPrescriptionMedicine"
                         :disabled="canNotAddPrescriptionMedicine()">新增药品</el-button>
              <div style="text-align: center;margin-bottom: 5px;">处方单原始金额：￥{{totalMedicinePrice}}</div>
              <div style="text-align: center;margin-bottom: 5px;">处方单医保金额：￥{{totalInsuranceMedicinePrice}}</div>
              <el-button v-if="prescriptionStatus==='05'" type="primary" style="width: 100%;margin: 0 auto;"
                         :disabled="prescriptionMedicineArrIsEmpty()" @click="commitPrescription">提交处方单</el-button>
              <div v-else style="font-size: 14px;font-weight: bold;text-align: center;">处方单已提交，诊断如下：</div>
              <el-input
                  :disabled="prescriptionStatus!=='05'"
                  v-model="prescriptionDiagnosis"
                  maxlength="50"
                  style="width: 100%;margin: 5px auto;"
                  placeholder="请输入诊断结果："
                  show-word-limit
                  type="textarea"
                  :autosize="{minRows: 3,maxRows: 3}"
                  resize="none"
              />
            </el-col>
            <!--展示处方单药品信息和基本操作-->
            <el-col :span="20" style="margin: auto 0">
              <div style="text-align: center;margin-bottom: 2px;">当前就诊患者的处方药品明细</div>
              <el-table :data="prescriptionMedicineArr" style="width: 100%;height: 28vh;">
                <el-table-column prop="name" label="药品名称" align="center" />
                <el-table-column prop="instruction" label="用药指导" align="center" width="300px"/>
                <el-table-column prop="number" label="数量" align="center"/>
                <el-table-column prop="price" label="价格" align="center"/>
                <el-table-column prop="insurancePrice" label="医保价格" align="center"/>
                <el-table-column label="操作" align="center">
                  <template #default="scope">
                    <el-button link type="primary" @click="editPrescriptionMedicine(scope.row.medicineId)" :disabled="prescriptionStatus!=='05'">编辑</el-button>
                    <el-button link type="primary" @click="deletePrescriptionMedicine(scope.row.medicineId,scope.row.name)" :disabled="prescriptionStatus!=='05'">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-card>
      </el-main>
    </el-container>
  </div>
  <!--点击“新增检查项”按钮，出现的弹窗，用于展示可用检查项目列表-->
  <el-dialog title="可用检查项目列表" v-model="showInspectionItemDialogVisible"
             style="width:1000px;padding:40px;" :before-close="handleCloseShowInspectionItem">
    <el-card style="margin-bottom: 5px;">
      <el-form :inline="true" style="margin-left: 30px;">
        <el-form-item label="检查项名称" style="margin: auto 20px;">
          <el-input placeholder="请输入内容" v-model="searchInspectionItemForm.name"
                    @keydown.enter="loadInspectionItem"></el-input>
        </el-form-item>
        <el-form-item label="检查方法" style="margin: auto 20px;">
          <el-input placeholder="请输入内容" v-model="searchInspectionItemForm.method"
                    @keydown.enter="loadInspectionItem"></el-input>
        </el-form-item>
        <el-form-item style="margin: auto 20px;">
          <el-button @click="resetSearchInspectionItem">重置</el-button>
          <el-button type="primary" @click="loadInspectionItem">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-table :data="inspectionItemArr" style="width: 100%;">
        <el-table-column prop="name" label="检查项目" align="center" />
        <el-table-column prop="code" label="项目编号" align="center" />
        <el-table-column prop="insuranceCode" label="医保编号" align="center" />
        <el-table-column prop="method" label="检查方法" align="center" />
        <el-table-column prop="remark" label="备注" align="center" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" :disabled="alreadyAddInspectionItem(scope.row.id)" @click="addInspectionSub
                       (scope.row.id,scope.row.name,scope.row.price,scope.row.insuranceCode)">新增</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </el-dialog>
  <!--点击“新增药品”按钮，出现的弹窗，用于展示可以开具的处方药-->
  <el-dialog title="可开具的处方药品" v-model="showMedicineDialogVisible"
             style="width:1500px;padding:40px;" :before-close="handleCloseShowMedicine">
    <el-card style="margin-bottom: 5px;">
      <el-form :inline="true" style="margin-left: 30px;">
        <el-form-item label="药品名称" style="margin: auto 20px;">
          <el-input placeholder="请输入内容" v-model="searchMedicineForm.name"
                    @keydown.enter="loadMedicine"></el-input>
        </el-form-item>
        <el-form-item label="药品剂型" style="margin: auto 20px;">
          <el-input placeholder="请输入内容" v-model="searchMedicineForm.dosage"
                    @keydown.enter="loadMedicine"></el-input>
        </el-form-item>
        <el-form-item label="生产厂家" style="margin: auto 20px;">
          <el-input placeholder="请输入内容" v-model="searchMedicineForm.manufacturer"
                    @keydown.enter="loadMedicine"></el-input>
        </el-form-item>
        <el-form-item label="功能主治" style="margin: auto 20px;">
          <el-input placeholder="请输入内容" v-model="searchMedicineForm.indication"
                    @keydown.enter="loadMedicine"></el-input>
        </el-form-item>
        <el-form-item style="margin: auto 20px;">
          <el-button @click="resetSearchMedicine">重置</el-button>
          <el-button type="primary" @click="loadMedicine">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-table :data="medicineArr" style="width: 100%;">
        <el-table-column prop="name" label="药品名称" align="center" />
        <el-table-column prop="category" label="药品分类" align="center"/>
        <el-table-column prop="specification" label="药品规格" align="center"/>
        <el-table-column prop="dosage" label="药品剂型" align="center"/>
        <el-table-column prop="manufacturer" label="生产厂家" align="center"/>
        <el-table-column prop="indication" label="功能主治" align="center"/>
        <el-table-column prop="adverseEffect" label="不良反应" align="center"/>
        <el-table-column prop="insuranceCode" label="医保编号" align="center"/>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" :disabled="alreadyAddMedicine(scope.row.id)" @click="addPrescriptionMedicine(
                       scope.row.id,scope.row.name,scope.row.specification,scope.row.dosage,
                       scope.row.manufacturer,scope.row.price,scope.row.insuranceCode)">新增</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </el-dialog>
  <!--点击检查项的“新增”或“编辑”按钮，出现的弹窗，用于新增或修改具体的检查项-->
  <el-dialog :title="inspectionItemDialogTitle" v-model="inspectionItemDialogVisible"
             style="width:1000px;padding:40px;" :before-close="handleCloseInspectionItem">
    <el-form label-width="100px">
      <el-form-item label="检查项目名称">
        <el-input v-model="saveInspectionSubForm.name" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="检查原因">
        <el-input
            v-model="saveInspectionSubForm.reason"
            maxlength="50"
            style="width: 100%;"
            placeholder="请输入检查原因："
            show-word-limit
            type="textarea"
            :autosize="{minRows: 3,maxRows: 3}"
            resize="none"
        />
      </el-form-item>
      <el-form-item label="检查要求">
        <el-input
            v-model="saveInspectionSubForm.standard"
            maxlength="50"
            style="width: 100%;"
            placeholder="请输入检查要求："
            show-word-limit
            type="textarea"
            :autosize="{minRows: 3,maxRows: 3}"
            resize="none"
        />
      </el-form-item>
      <el-form-item label="备注">
        <el-input
            v-model="saveInspectionSubForm.remark"
            maxlength="50"
            style="width: 100%;"
            placeholder="请输入备注："
            show-word-limit
            type="textarea"
            :autosize="{minRows: 3,maxRows: 3}"
            resize="none"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleCloseInspectionItem">取消</el-button>
      <el-button type="primary" @click="saveInspectionSub">保存</el-button>
    </template>
  </el-dialog>
  <!--点击处方药品的“新增”或“编辑”按钮，出现的弹窗，用于开具或修改具体的处方药品-->
  <el-dialog :title="medicineDialogTitle" v-model="medicineDialogVisible"
             style="width:1000px;padding:40px;" :before-close="handleCloseMedicine">
    <el-form label-width="100px" label-position="top">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="药品名">
            <el-input v-model="savePrescriptionMedicineForm.name" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="药品规格">
            <el-input v-model="savePrescriptionMedicineForm.specification" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="药品剂型">
            <el-input v-model="savePrescriptionMedicineForm.dosage" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生产厂家">
            <el-input v-model="savePrescriptionMedicineForm.manufacturer" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="用药指导">
        <el-input
            v-model="savePrescriptionMedicineForm.instruction"
            maxlength="50"
            style="width: 100%;"
            placeholder="请输入用药指导："
            show-word-limit
            type="textarea"
            :autosize="{minRows: 3,maxRows: 3}"
            resize="none"
        />
      </el-form-item>
      <el-form-item label="药品数量">
        <el-input-number placeholder="请输入正整数" v-model="savePrescriptionMedicineForm.number"
                         :step="1" step-strictly :min="1" style="width: 200px"></el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleCloseMedicine">取消</el-button>
      <el-button type="primary" @click="savePrescriptionMedicine">保存</el-button>
    </template>
  </el-dialog>
  <!--点击退号按钮，出现退号弹窗  -->
  <el-dialog title="请输入退号原因：" v-model="refuseReasonDialogVisible"
             style="width:500px;padding: 40px;" :before-close="handleCloseRefuseReason">
    <el-form label-width="100px">
      <el-form-item label="退号原因">
        <el-input
            v-model="refuseReason"
            maxlength="50"
            style="width: 100%;margin-bottom: 5px"
            placeholder="请输入："
            show-word-limit
            type="textarea"
            :autosize="{minRows: 3,maxRows: 3}"
            resize="none"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleCloseRefuseReason">取消</el-button>
      <el-button type="primary" @click="changeAttendanceRecordStatus('40')">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
  import {ref,onMounted} from "vue";
  import { ElMessage } from "element-plus";
  import {Avatar} from '@element-plus/icons-vue';
  import axios from "axios";
  import qs from "qs";

  //第零部分变量：localStorage
  //定义变量用于保存医生id
  const doctorId = getUserInfo().id

  //第一部分变量：header部分
  //定义变量用来保存选择的患者id
  const selectedId = ref('');
  //定义变量用来保存当前患者的就诊记录id
  let attendanceRecordId = '';
  //定义数组用来保存患者id对应的患者信息
  const patientById = ref([]);
  //定义数组用来保存 属于当前医生 且 接诊中 的患者信息（一进入页面就加载）
  const patientArr = ref([]);
  //定义变量用来保存病人的主诉
  const chiefComplaint = ref('');
  //定义变量用来保存病人的既往病史
  const pastMedicalHistory = ref('');

  //第二部分变量：检查单部分
  //定义变量用来记录当前患者的检查单id
  let inspectionId = '';
  //定义变量用来保存当前检查单状态
  const inspectionStatus = ref('05');
  //定义变量用来保存当前检查单初始金额
  const totalInspectionPrice = ref('');
  //定义变量用来保存当前检查单医保金额
  const totalInsuranceInspectionPrice = ref('');
  //定义变量用来保存检查单备注
  const inspectionRemark = ref('');
  //定义数组用来保存当前选中的患者的检查单子项信息
  //这个信息需要用检查单id去查询
  const inspectionSubArr = ref([]);

  //第三部分变量：处方单部分
  //定义变量用来记录当前患者的处方单id
  let prescriptionId = '';
  //定义变量用来保存当前处方单状态
  const prescriptionStatus = ref('05');
  //定义变量用来保存当前处方单初始金额
  const totalMedicinePrice = ref('');
  //定义变量用来保存当前处方单医保金额
  const totalInsuranceMedicinePrice = ref('');
  //定义变量用来保存处方单诊断结果
  const prescriptionDiagnosis = ref('');
  //定义数组用来保存当前选中的患者的处方单药品信息
  //这个信息需要用处方单id去查询
  const prescriptionMedicineArr = ref([])

  //第四部分变量：弹窗部分
  //定义变量控制弹窗是否显示
  const showInspectionItemDialogVisible = ref(false);
  const showMedicineDialogVisible = ref(false);
  const inspectionItemDialogVisible = ref(false);
  const medicineDialogVisible = ref(false);
  const refuseReasonDialogVisible = ref(false);
  //定义变量用来保存弹窗的标题
  const inspectionItemDialogTitle = ref('新增检查项');
  const medicineDialogTitle = ref('开具处方药品');
  //搜索可用检查项时，定义对象用来封装搜索表单中的条件
  const searchInspectionItemForm = ref({})
  //搜索可开具的处方药品时，定义对象用来封装搜索表单中的条件
  const searchMedicineForm = ref({})
  //定义数组用来保存所有可用检查项目 inspectionItemArr
  const inspectionItemArr = ref([]);
  //定义数组用来保存所有可开具的处方药品 medicineArr
  const medicineArr = ref([]);
  //定义对象用来保存新增检查单子项时提交的数据
  const saveInspectionSubForm = ref({});
  //定义对象用来保存新增处方药品时提交的数据
  const savePrescriptionMedicineForm = ref({});
  //定义变量用来保存退号原因
  const refuseReason = ref('');

  //第零部分方法：一进入页面就加载
  //一进入页面就调用方法获取当前医生正在接诊的所有患者信息
  onMounted(() => {
    ElMessage.success('欢迎进入患者管理页面！请先选择患者！');
    getPatientInfoList();
  });

  //第一部分方法：header部分
  //定义方法用来展示具体的患者信息，且选中哪个患者，就将他的就诊记录id保存在attendanceRecordId中
  const selectPatient = () => {
    //自动保存上一个患者信息
    if(attendanceRecordId){
      updateAttendanceRecord('');
    }
    //清空上一个患者信息
    clearPatientInfo();
    //按照选择的患者id加载当前患者相关信息
    for(let i=0;i<patientArr.value.length;i++){
      if(patientArr.value[i].patientId === selectedId.value){
        patientById.value.push(patientArr.value[i]);
        attendanceRecordId = patientArr.value[i].id;
        inspectionId = patientArr.value[i].inspectionId;
        //加载患者的检查单相关信息
        displayInspection();
        displayInspectionSubList();
        prescriptionId = patientArr.value[i].prescriptionId;
        //加载患者的处方单相关信息
        displayPrescription();
        displayPrescriptionMedicineList();
        chiefComplaint.value = patientArr.value[i].chiefComplaint;
        if(chiefComplaint.value === 'null'){
          chiefComplaint.value = '';
        }
        pastMedicalHistory.value = patientArr.value[i].pastMedicalHistory;
        if(pastMedicalHistory.value === 'null'){
          pastMedicalHistory.value = '';
        }
        return;
      }
    }
  }
  //将修改就诊记录的代码抽成一个方法方便复用
  const updateAttendanceRecord = (status) => {
    //需要将主诉、既往病史、退号原因一起保存到就诊记录的remark中，先用#$拼起来，再给后端发请求
    let remark = chiefComplaint.value+'#$'+pastMedicalHistory.value+'#$'+refuseReason.value;
    //给后端发请求
    let data = {id: attendanceRecordId, status: status, remark: remark};
    axios.post(BASE_URL+'/v1/attendance/update', data).then(response => {
      if(response.data.code === 2001){
        //调用方法重新获取当前医生正在接诊的所有患者信息
        getPatientInfoList();
      } else {
        ElMessage.error('自动保存患者就诊信息失败！');
      }
    });
  }
  //将清空患者信息的代码抽成一个方法方便复用
  const clearPatientInfo = () => {
    attendanceRecordId = '';
    inspectionId = '';
    prescriptionId = '';
    patientById.value = [];
    chiefComplaint.value = '';
    pastMedicalHistory.value = '';
    inspectionRemark.value = '';
    prescriptionDiagnosis.value = '';
    inspectionStatus.value = '05';
    prescriptionStatus.value = '05';
    totalInspectionPrice.value = '';
    totalInsuranceInspectionPrice.value = '';
    totalMedicinePrice.value = '';
    totalInsuranceMedicinePrice.value = '';
    inspectionSubArr.value = [];
    prescriptionMedicineArr.value = [];
  }

  //定义方法用来获取当前医生正在接诊的所有患者信息，注意：
  //入参：要从localStorage中获取医生id，并且就诊记录表中status字段的值为'30'
  //出参：返回的data要存入patientArr中
  const getPatientInfoList = () => {
    let data = qs.stringify({doctorId:doctorId, status:'20'});
    axios.get(BASE_URL+'/v1/attendance/select?'+data).then((response)=>{
      if(response.data.code===2001){
        patientArr.value = response.data.data;
      } else {
        ElMessage.error('加载待接诊的患者信息失败，请刷新页面！');
      }
    });
  }

  //定义方法用于修改就诊记录的状态
  const changeAttendanceRecordStatus = (status) => {
    //当status==='30'(完成接诊)时，判断检查单和处方单是否提交
    if(status==='30'){
      //询问是否确认点击按钮
      if(!confirm('您确认完成接诊么？点击后将不能继续接诊该患者！')){
        return;
      }
      //要求提交检查单和处方单
      if(inspectionSubArr.value.length !== 0 && inspectionStatus.value === '05'){
        ElMessage.error("您有未提交的检查单，请先提交检查单！");
        return;
      }
      if(prescriptionMedicineArr.value.length !== 0 && prescriptionStatus.value === '05'){
        ElMessage.error("您有未提交的处方单，请先提交处方单！");
        return;
      }
    }
    //当status==='40'(退号)时，判断退号原因是否为空，为空则弹出退号原因输入框的弹窗并return
    if(status==='40'){
      //询问是否确认点击按钮
      if(!confirm('您确认点击按钮么？')){
        return;
      }
      if(!refuseReason.value || refuseReason.value.trim()===''){
        refuseReasonDialogVisible.value = true;
        ElMessage.info('请输入退号原因！');
        return;
      }
      //退号原因不为空，证明输入了退号原因，关闭弹窗
      refuseReasonDialogVisible.value = false;
    }
    //修改就诊记录
    updateAttendanceRecord(status);
    //修改完状态后清空当前患者id值，清空退号原因
    selectedId.value = '';
    refuseReason.value = '';
    //清空当前患者信息
    clearPatientInfo();
  }
  //定义方法用于控制“完成接诊”按钮是否可用
  const canNotFinish = () => {
    if (!selectedId.value) {
      return true;
    }
    return inspectionSubArr.value.length === 0 && prescriptionMedicineArr.value.length === 0;
  }
  //定义方法用于控制“退号”按钮是否可用
  const canNotRefuse = () => {
    if (!selectedId.value) {
      return true;
    }
    return inspectionSubArr.value.length !== 0 || prescriptionMedicineArr.value.length !== 0;
  }

  //第二部分方法：检查单部分
  //定义方法用于展示检查单信息
  const displayInspection = () => {
    axios.get(BASE_URL+'/v1/inspection/query/'+inspectionId).then(response => {
      if (response.data.code === 2001) {
        inspectionStatus.value = response.data.data.status;
        totalInspectionPrice.value = response.data.data.price;
        totalInsuranceInspectionPrice.value = response.data.data.insurancePrice;
        inspectionRemark.value = response.data.data.remark;
      } else {
        ElMessage.error('查询检查单失败！');
      }
    });
  }

  //定义方法用于展示检查单子项列表
  const displayInspectionSubList = () => {
    axios.get(BASE_URL+'/v1/inspection/select/'+inspectionId).then(response => {
      if (response.data.code === 2001) {
        inspectionSubArr.value = response.data.data;
      } else {
        ElMessage.error('查询检查单子项失败！');
      }
    });
  }
  //定义检查单子项状态的转换器
  const inspectionSubItemStatusFormatter = (row,column,cellValue,index)=>{
    switch (cellValue) {
      case '10':
        return '结果未出';
      case '20':
        return '结果已出';
    }
  }
  const inspectionSubItemUpdateTimeFormatter = (row,column,cellValue,index)=>{
    if(!cellValue){
      return '无更新时间'
    }else{
      return cellValue;
    }
  }

  //点击“新增检查项”按钮时调用，用于展示可用检查项
  const showAddInspectionSub = () => {
    showInspectionItemDialogVisible.value = true;
    loadInspectionItem();
  }
  //定义方法用于控制该按钮是否可用
  const canNotAddInspectionItem = () => {
    if (!selectedId.value) {
      return true;
    }
    return inspectionStatus.value !== '05';
  }

  //定义方法用于查看检查结果
  const showResult = (resultUrl) => {
    window.open(resultUrl, '_blank');
  }

  //定义方法用于修改检查单子项
  const editInspectionSub = (inspectionItemId,name) => {
    inspectionItemDialogTitle.value = '修改检查项';
    inspectionItemDialogVisible.value = true;
    //回显数据
    saveInspectionSubForm.value.name=name;
    saveInspectionSubForm.value.inspectionItemId = inspectionItemId;
    axios.get(BASE_URL+'/v1/inspection/selectOne/'+inspectionItemId+'/'+inspectionId).then(response=>{
      if(response.data.code===2001){
        saveInspectionSubForm.value.reason = response.data.data.reason;
        saveInspectionSubForm.value.standard = response.data.data.standard;
        saveInspectionSubForm.value.remark = response.data.data.remark;
      }else {
        ElMessage.error('回显检查项失败！');
      }
    })
  }

  //定义方法用于删除检查单子项
  const deleteInspectionSub = (inspectionItemId,price,insurancePrice) => {
    if(!confirm('您确认删除该检查项吗？删除后不可撤销！')){
      return;
    }
    let data = qs.stringify({
      inspectionId:inspectionId,
      inspectionItemId:inspectionItemId,
      price:price,
      insurancePrice:insurancePrice
    });
    axios.post(BASE_URL+'/v1/inspection/delete',data).then(response=>{
      if(response.data.code===2001){
        ElMessage.success('删除检查项成功！');
        //重新获取当前检查单信息和检查子项列表信息
        displayInspection();
        displayInspectionSubList();
      } else {
        ElMessage.error('删除检查项失败！');
      }
    });
  }

  //定义方法用来提交检查单信息
  const commitInspection = ()=>{
    if(!confirm('确认提交检查单信息？提交后不可新增和修改！')){
      return;
    }
    let data = {id:inspectionId, status: '10', remark:inspectionRemark.value}
    axios.post(BASE_URL+'/v1/inspection/update',data).then(response=>{
      if(response.data.code===2001){
        ElMessage.success('提交检查单信息成功！');
        displayInspection();
      } else {
        ElMessage.error('提交检查单信息失败！');
      }
    });
  }
  //控制该按钮是否可用
  const inspectionSubArrIsEmpty = () => {
    if (!selectedId.value) {
      return true;
    }
    return inspectionSubArr.value.length===0;
  }

  //第三部分方法：处方单部分
  //定义方法用于展示处方单信息
  const displayPrescription = () => {
    let data = qs.stringify({id:prescriptionId});
    axios.get(TEST_URL+'/v1/prescription/selectPrescription?'+data).then((res) => {
      if (res.data.code === 2001){
        //返回当前处方单的药品总金额
        totalMedicinePrice.value = res.data.data[0].price;
        //返回当前处方单的医保药总金额
        totalInsuranceMedicinePrice.value = res.data.data[0].insurancePrice;
        prescriptionStatus.value = res.data.data[0].status;
        prescriptionDiagnosis.value= res.data.data[0].diagnosis;
      } else {
        ElMessage.error('查询处方单失败！');
      }
    });
  }

  //定义方法用于展示处方单子项列表
  const displayPrescriptionMedicineList = () => {
    //获取当前处方单中的药品信息
    let data = qs.stringify({ prescriptionId: prescriptionId });
    axios.get(TEST_URL+'/v1/prescription/selectPrescriptionMedicine?'+data).then((res) => {
      if (res.data.code === 2001){
        //将当前查询到的信息赋值给prescriptionMedicineArr
        prescriptionMedicineArr.value = res.data.data;
      } else {
        ElMessage.error('查询处方单药品失败！');
      }
    });
  }

  //点击“新增药品”按钮时调用，用于展示可以新增的处方药品
  const showAddPrescriptionMedicine = () => {
    showMedicineDialogVisible.value = true;
    loadMedicine();
  }
  //定义方法用于控制该按钮是否可用
  const canNotAddPrescriptionMedicine = () => {
    if (!selectedId.value) {
      return true;
    }
    return prescriptionStatus.value !== '05';
  }

  //定义方法用于修改处方单药品
  const editPrescriptionMedicine = (medicineId) => {
    medicineDialogTitle.value = '修改处方药品';
    medicineDialogVisible.value = true;
    //获取当前处方单中的药品信息
    let data = qs.stringify({ prescriptionId: prescriptionId, medicineId: medicineId});
    axios.get(TEST_URL+'/v1/prescription/selectPrescriptionMedicine?'+data).
    then((res) => {
      if (res.data.code === 2001){
        //将当前查询到的信息赋值给savePrescriptionMedicineForm
        savePrescriptionMedicineForm.value = res.data.data[0];
      }else {
        ElMessage.error('回显处方药品失败！');
      }
    });
  }

  //定义方法用于删除处方单药品
  const deletePrescriptionMedicine = (medicineId,name) => {
    if(!confirm('您确认删除药品：'+name+'吗？删除后不可撤销！')){
      return;
    }
    let data = qs.stringify({prescriptionId: prescriptionId, medicineId: medicineId });
    axios.post(TEST_URL+'/v1/prescription/deletePrescriptionMedicine?'+data).then((res) => {
      if (res.data.code === 2001){
        ElMessage.success('药品：'+name+'删除成功！')
        displayPrescription();
        displayPrescriptionMedicineList();
      }else {
        ElMessage.error('药品：'+name+'删除失败，请稍后再试！')
      }
    });
  }

  //定义方法用来提交处方单信息
  const commitPrescription = ()=>{
    if(!confirm('确认提交处方单信息？提交后不可新增和修改！')){
      return
    }
    if(!prescriptionDiagnosis.value || prescriptionDiagnosis.value.trim()===''){
      ElMessage.error('请填写处方单诊断结果！');
      return;
    }
    let data = {id:prescriptionId, status:'10', diagnosis:prescriptionDiagnosis.value, remark: chiefComplaint.value}
    axios.post(BASE_URL+'/v1/prescription/update',data).then(response=>{
      if(response.data.code===2001){
        ElMessage.success('提交处方单信息成功！');
        displayPrescription();
      } else {
        ElMessage.error('提交处方单信息失败！');
      }
    });
  }
  //控制该按钮是否可用
  const prescriptionMedicineArrIsEmpty = () => {
    if(!selectedId.value){
      return true;
    }
    return prescriptionMedicineArr.value.length === 0;
  }

  //第四部分方法：弹窗部分
  //定义方法处理弹窗关闭
  const handleCloseShowInspectionItem = () => {
    if(!confirm('您确认要关闭本弹窗吗?')){
      return
    }
    showInspectionItemDialogVisible.value = false;
    searchInspectionItemForm.value = {};
  }
  const handleCloseShowMedicine = () => {
    if(!confirm('您确认要关闭本弹窗吗?')){
      return
    }
    showMedicineDialogVisible.value = false;
    searchMedicineForm.value = {};

  }
  const handleCloseInspectionItem = () => {
    if(!confirm('您确认要关闭本弹窗吗?')){
      return
    }
    inspectionItemDialogVisible.value = false;
    saveInspectionSubForm.value = {};
  }
  const handleCloseMedicine = () => {
    if(!confirm('您确认要关闭本弹窗吗?')){
      return
    }
    medicineDialogVisible.value = false;
    savePrescriptionMedicineForm.value = {};
  }
  const handleCloseRefuseReason = () => {
    if(!confirm('您确认要关闭本弹窗吗?')){
      return
    }
    refuseReasonDialogVisible.value = false;
    refuseReason.value = '';
  }

  //定义方法用来搜索符合条件的检查项
  const loadInspectionItem = () => {
    let data=searchInspectionItemForm.value;
    data = qs.stringify(data);
    axios.get(BASE_URL+'/v1/inspection/item/select?'+data).then(response=>{
      if(response.data.code===2001){
        inspectionItemArr.value = response.data.data;
      } else {
        ElMessage.error('查询可用检查项失败！');
      }
    });
  }
  //定义重置搜索检查项的方法
  const resetSearchInspectionItem = () => {
    searchInspectionItemForm.value = {};
    loadInspectionItem();
  }
  //定义方法用于控制检查项对话框中的新增按钮是否可用
  const alreadyAddInspectionItem = (inspectionItemId) =>{
    for(let i=0;i<inspectionSubArr.value.length;i++){
      if(inspectionSubArr.value[i].inspectionItemId===inspectionItemId){
        return true;
      }
    }
    return false;
  }

  //定义方法用来搜索符合条件的处方药品
  const loadMedicine = () => {
    let data = qs.stringify(searchMedicineForm.value);
    axios.post(TEST_URL+"/v1/medicine/select?"+data).then((res) => {
      if (res.data.code === 2001){
        medicineArr.value = res.data.data.list;
      }else {
        ElMessage.error('查询可用处方药品失败！');
      }
    });
  }
  //定义重置搜索处方药品的方法
  const resetSearchMedicine = () => {
    searchMedicineForm.value = {};
    loadMedicine();
  }
  //定义方法用于控制药品对话框中的新增按钮是否可用
  const alreadyAddMedicine = (medicineId) =>{
    for(let i=0;i<prescriptionMedicineArr.value.length;i++){
      if(prescriptionMedicineArr.value[i].medicineId===medicineId){
        return true;
      }
    }
    return false;
  }

  //定义方法用来展示新增检查单子项弹窗
  const addInspectionSub = (id,name,price,insuranceCode) => {
    inspectionItemDialogTitle.value = '新增检查项';
    //showInspectionItemDialogVisible.value = false;
    inspectionItemDialogVisible.value = true;
    saveInspectionSubForm.value.name = name;
    saveInspectionSubForm.value.inspectionItemId = id;
    saveInspectionSubForm.value.price = price;
    saveInspectionSubForm.value.insuranceCode = insuranceCode;
  }

  //定义方法用来处理 新增/修改 检查单子项，并且数据保存到后端
  const saveInspectionSub = () => {
    saveInspectionSubForm.value.inspectionId = inspectionId;
    let data = qs.stringify(saveInspectionSubForm.value);
    //先判断是新增还是修改
    if(inspectionItemDialogTitle.value==='新增检查项'){
      axios.post(BASE_URL+"/v1/inspection/insert",data).then((res)=>{
        if(res.data.code===2001){
          ElMessage.success('新增检查项成功！');
          //重新获取当前检查单子项列表
          displayInspection();
          displayInspectionSubList();
          saveInspectionSubForm.value = {};
          //关闭弹窗
          inspectionItemDialogVisible.value = false;
        }else{
          ElMessage.error('新增检查项失败，请稍后再试！');
        }
      });
    }else{
      axios.post(BASE_URL+'/v1/inspection/edit',data).then((response)=>{
        if(response.data.code===2001){
          ElMessage.success('修改检查项成功！');
          //重新获取当前检查单子项列表
          displayInspectionSubList();
          saveInspectionSubForm.value = {};
          //关闭弹窗
          inspectionItemDialogVisible.value = false;
        } else {
          ElMessage.error('修改检查项失败，请稍后再试！');
        }
      });
    }
  }

  //定义方法用来展示新增处方单药品弹窗
  const addPrescriptionMedicine = (id,name,specification,dosage,manufacturer,price,insuranceCode) => {
    medicineDialogTitle.value = '开具处方药品';
    //showMedicineDialogVisible.value = false;
    medicineDialogVisible.value = true;
    savePrescriptionMedicineForm.value.name = name;
    savePrescriptionMedicineForm.value.specification = specification;
    savePrescriptionMedicineForm.value.dosage = dosage;
    savePrescriptionMedicineForm.value.manufacturer = manufacturer;
    savePrescriptionMedicineForm.value.medicineId = id;
    savePrescriptionMedicineForm.value.price = price;
    savePrescriptionMedicineForm.value.insuranceCode = insuranceCode;
  }

  //定义方法用来处理 新增/修改 处方单药品，并且数据保存到后端
  const savePrescriptionMedicine = () => {
    savePrescriptionMedicineForm.value.prescriptionId=prescriptionId;
    if (!savePrescriptionMedicineForm.value.instruction || savePrescriptionMedicineForm.value.instruction.trim()===''){
      ElMessage.error('用药指导不能为空！');
      return;
    }
    let data = qs.stringify(savePrescriptionMedicineForm.value);
    axios.post(TEST_URL+"/v1/prescription/savePrescriptionMedicine?"+data).then((res)=>{
      if (res.data.code === 2001){
        ElMessage.success(savePrescriptionMedicineForm.value.name+'： 数量['+savePrescriptionMedicineForm.value.number+']，保存成功!');
        //关闭弹窗
        medicineDialogVisible.value = false;
        //重置表单数据
        savePrescriptionMedicineForm.value = {};
        //加载处方单和处方单药品信息
        displayPrescription();
        displayPrescriptionMedicineList();
      }else {
        ElMessage.error('保存失败，请稍后再试！');
      }
    });
  }
</script>

<style scoped>

</style>